package com.ctz.commonframe.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import android.graphics.Bitmap;
import android.text.TextUtils;

public class IOUtil {
	private static final String TAG = "IOUtil";
	
	/**
	 * write the String content to file
	 * 
	 * @param path   
	 * @param content
	 * @param isAppend
	 */
	public static void writeString2File(String path, String content, boolean isAppend){
		if(TextUtils.isEmpty(path) || TextUtils.isEmpty(content)){
			Logger.e(TAG, "params has empty value int writeString2File");
			return;
		}
		FileWriter fw = null;
		try {
			File file = new File(path);
			checkFile(file, isAppend);
			fw = new FileWriter(file, isAppend);  
		    fw.write(content);  
		    fw.flush();
		    fw.close();
		} catch (Exception e) {  
		    e.printStackTrace();  
		} 
	}
	
	/**
	 * write the bitmap to file
	 * 
	 * @param path
	 * @param bitmap
	 */
	public static void writeBitmap2File(String path, Bitmap bitmap){
		if(TextUtils.isEmpty(path) || bitmap == null){
			Logger.e(TAG, "params has empty value int writeBitmap2File");
			return;
		}
	    FileOutputStream fos = null;
	    File file = new File(path);
	    try {
	    	checkFile(file, false);
	    	fos = new FileOutputStream(file);     
	        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
	    } catch (IOException e) {
	        e.printStackTrace();
	    } finally {
	        if (fos != null) {
	        	try {
	                 fos.close();
	            } catch (IOException e) {
	            	e.printStackTrace();
	            }
	        }
	    }
	}
	
	/**
	 * 读取文件
	 * 
	 * @param path 文件路径
	 * @return
	 */
	public static String readFile(String path){
		if(TextUtils.isEmpty(path)){
			Logger.e(TAG, "params has empty value int readFile");
			return null;
		}
		File file = new File(path);
		return readFile(file);
	}
	
	/**
	 * 读取文件
	 * 
	 * @param file 文件
	 * @return
	 */
	public static String readFile(File file){
		if(!file.exists()){
			Logger.e(TAG, "file not found in readFile");
			return null;
		}
		
		StringBuffer sb = new StringBuffer();  
		try {  
		    BufferedReader br = new BufferedReader(new FileReader(file));  
		    String readline = "";  
		    while ((readline = br.readLine()) != null) {  
		        sb.append(readline);  
		    }  
		    br.close();  
		} catch (Exception e) {  
		    e.printStackTrace();  
		} 
		return sb.toString();
	}
	
	
	private static void checkFile(File file, boolean isAppend) throws IOException{
		if(file != null){
			if(!file.getParentFile().exists()){
				file.getParentFile().mkdirs();
			}
			if(file.exists()){
				if(!isAppend)
					file.delete();
			}else{
				file.createNewFile();
			}
		}
	}
}
